﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using Casamiel.API.Application;
using Casamiel.API.Application.Commands;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Models.Meituan;
using Casamiel.API.Application.Models.Store;
using Casamiel.API.Application.Services;
using Casamiel.Application;
using Casamiel.Application.Commands;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Common.Utilities;
using Casamiel.Domain.Entity;
using Casamiel.Domain.Request;
using Casamiel.Domain.Request.IC;
using Casamiel.Domain.Response;
using Enyim.Caching;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using static Casamiel.API.Application.Models.Store.AddMeiTuanOrderReq;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers.V2
{
    /// <summary>
    /// 美团接口
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("2.0")]
    [Route("api/v{api-version:apiVersion}/[controller]")]
    [ApiController]
    public class MeiTuanController : Controller
    {
        private readonly NLog.ILogger _logger = NLog.LogManager.GetLogger("MeiTuanOrderService");
        private readonly NLog.ILogger _stocklogger = NLog.LogManager.GetLogger("StockService");
        private readonly IIcApiService _icApiService;
        private readonly IStoreApiService _storeApiService;
        private readonly IStoreService _storeService;
        private readonly INoticeService _notice;
        private readonly ICasaMielSession _session;
        private readonly IThirdPartyPlatformConfigService _thirdPartyPlatformConfigService;
        private readonly string _apitoken;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IMemberCardService _memberCardService;
        private readonly IErrorLogService _errorLogService;
        private readonly IMemcachedClient _memcachedClient;
        private readonly IMediator _mediator;
        private readonly string _memcachedPre;
        private readonly string _apiname = "";
        private readonly IOrderService _order;
        /// <summary>
        /// 
        /// 
        /// </summary>
        /// <param name="notice"></param>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="storeApiService">Store API service.</param>
        /// <param name="store">Store.</param>
        /// <param name="session">Session.</param>
        /// <param name="snapshot">snapshot</param>
        /// <param name="thirdPartyPlatformConfigService"></param>
        /// <param name="httpClientFactory"></param>
        /// <param name="memberCardService"></param>
        /// <param name="errorLogService"></param>
        /// <param name="mediator"></param>
        /// <param name="memcachedClient"></param>
        /// <param name="order"></param>
        /// 
        public MeiTuanController(INoticeService notice, IIcApiService iicApiService, IStoreApiService storeApiService, IStoreService store, ICasaMielSession session, IOptionsSnapshot<CasamielSettings> snapshot,
                                 IThirdPartyPlatformConfigService thirdPartyPlatformConfigService, IHttpClientFactory httpClientFactory, IMemberCardService memberCardService, IErrorLogService errorLogService,
                                 IMediator mediator, IMemcachedClient memcachedClient, IOrderService order)
        {
            if (snapshot == null) {
                throw new ArgumentNullException(nameof(snapshot));
            }
            _notice = notice;
            _icApiService = iicApiService;
            _storeApiService = storeApiService;
            _storeService = store;
            _session = session;
            _apitoken = snapshot.Value.ApiToken;
            _thirdPartyPlatformConfigService = thirdPartyPlatformConfigService;
            _httpClientFactory = httpClientFactory;
            _memberCardService = memberCardService;
            _errorLogService = errorLogService;
            _mediator = mediator;
            _memcachedClient = memcachedClient;
            _memcachedPre = snapshot.Value.MemcachedPre;
            _apiname = snapshot.Value.ApiName;
            _order = order;
        }

        /// <summary>
        /// Adds the order.
        /// </summary>
        /// <returns>The order.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> AddOrder([FromBody] AddMeiTuanOrderReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            _logger.Trace($"AddOrder:{JsonConvert.SerializeObject(data)}");
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }

            var _cachekey = _memcachedPre + Constant.NEWMEITUANORDER + data.OrderId.ToString(CultureInfo.CurrentCulture);
            var a = _memcachedClient.Increment(_cachekey, 0, 1);
            if (a > 0) {
                return Ok(new { code = 0, msg = "" });
            }
            //明细
            List<GoodsDetail> details1 = JsonConvert.DeserializeObject<List<GoodsDetail>>(data.detail);
            var goodslist = new List<GoodsDetailExt>();

            var details = details1.Where(c => c.sku_id != "1").ToList();
            foreach (var item in details) {
                var goods = new GoodsDetailExt {
                    app_food_code = item.App_food_code,
                    box_num = Convert.ToInt32(decimal.Truncate(item.Box_num)),
                    cart_id = item.cart_id,
                    box_price = item.box_price,
                    foodShareFeeChargeByPoi = item.foodShareFeeChargeByPoi,
                    food_discount = item.food_discount,
                    food_name = item.food_name,
                    food_property = item.food_property,
                    price = item.price,
                    quantity = item.quantity,
                    sku_id = item.sku_id,
                    unit = item.unit

                };
                goodslist.Add(goods);

            }
            data.detail = JsonConvert.SerializeObject(goodslist);
            //优惠券
            var extrasDetails = JsonConvert.DeserializeObject<List<ExtrasDetail>>(data.extras);
            var orderentity = await _order.GetByOrderCodeAsync<ICasaMielSession>($"{data.OrderId}").ConfigureAwait(false);
            if (orderentity != null) {
                return Ok(new { code = 0, msg = "订单已存在！" });
            }

            //string a = "424009,424010,423986,419685,424151,42398,141784,424167";
            //List<string> blacklist = new List<string>();
            var drinkcmd = new GetDrinksGoodsIdsCommand();
            var blacklist = await _mediator.Send(drinkcmd).ConfigureAwait(false);
            //var drink = await _storeApiService.GetDrinksGoodsId().ConfigureAwait(false);
            //var rnt = JObject.Parse(drink);
            //if (rnt["ResultNo"].ToString() == "00000000")// "ResultNo": "00000000",
            //{
            //    blacklist = JsonConvert.DeserializeObject<List<string>>(rnt["Data"].ToString());
            //}
            //blacklist = a.Split(',').ToList();

            var shopid = data.ePoiId.ToInt32(0);
            var shopentity = await _storeService.GetByRelationIdAsync<ICasaMielSession>(shopid).ConfigureAwait(false);
            if (shopentity == null) {
                _logger.Trace($"门店不存在，美团ePoiId：{shopid}");
                return Ok(new { code = 0, msg = "门店不存在！" });
            }
            var mtentity = await _thirdPartyPlatformConfigService.FindAsync<ICasaMielSession>(shopid).ConfigureAwait(false);
            if (mtentity == null || mtentity.MeiTuanEnable == false) {
                _logger.Trace($"美团ePoiId：{shopid}");
                return Ok(new { code = 0, msg = "还未开通！" });
            }
            var packagingMoney = 0m;//包装费
            var orderDiscountMoney = 0;//data.originalPrice - data.total- data.shippingFee;//折扣
            var Orderoriginprice = 0m;//原价
            var shippingFee = data.ShippingFee;//运费
            var ptprice = new IcPriceReq { Shopid = shopid, Product = new List<ProductItemReq>() };

            var errlist = new List<string>();
            foreach (var item in details) {
                if (item.sku_id.ToInt32(0) == 0) {
                    //errlist.Add($"{item.food_name},sku不存在 ");
                    var info = $"{shopentity.StoreName}-{shopid},订单号：{data.OrderId},{item.food_name},sku不存在";
                    await _errorLogService.AddAsync<ICasaMielSession>(new Domain.ErrorLog { Url = "/api/v2/MeiTuan/AddOrder", Loginfo = info, OPTime = DateTime.Now, Type = 2 }).ConfigureAwait(false);
                    errlist.Add(info);
                }
                //if (item.sku_id.ToInt32(0) == 1 && item.price==0)
                //{
                //    details.Remove(item);
                //    continue;
                //}
                packagingMoney += item.Box_num * item.box_price;
                ptprice.Product.Add(new ProductItemReq { Pid = item.sku_id, Count = item.quantity });
            }
            if (errlist.Count > 0) {
                _logger.Error($"AddOrder:{JsonConvert.SerializeObject(new { code = 999, msg = String.Join(", ", errlist.ToArray()) })}");
                return Ok(new { code = 999, msg = String.Join(", ", errlist.ToArray()) });
            }
            var pzmodel = await _icApiService.Icprice(ptprice).ConfigureAwait(false);
            if (pzmodel.Product.Count > 0) {
                foreach (var item in details) {
                    var iteminfo = pzmodel.Product.Find(cw => cw.Pid == item.sku_id);
                    if (iteminfo != null) {
                        var total = iteminfo.Originprice * item.quantity;
                        Orderoriginprice += total;
                        if (blacklist.Contains(item.sku_id)) {
                            continue;
                        }
                        var goods = await _storeService.GetDetailV2ByReleationIdAsync<ICasaMielSession>(iteminfo.Pid.ToInt32(0)).ConfigureAwait(false);
                        if (goods == null) {
                            var info = $"{shopentity.StoreName}-{shopid},订单号：{data.OrderId},{item.food_name},sku:{item.sku_id},后台系统没产品信息";
                            await _errorLogService.AddAsync<ICasaMielSession>(new Domain.ErrorLog { Url = "/api/v2/MeiTuan/AddOrder", Loginfo = info, OPTime = DateTime.Now, Type = 2 }).ConfigureAwait(false);
                            errlist.Add(info);
                        }
                        if (iteminfo.Icprice != item.price) {
                            var info = $"{shopentity.StoreName}-{shopid},订单号：{data.OrderId},sku:{item.sku_id},{item.food_name},价格:{item.price},一网价格{iteminfo.Icprice}{iteminfo.Pname},sku{iteminfo.Pid}";
                            await _errorLogService.AddAsync<ICasaMielSession>(new Domain.ErrorLog { Url = "/api/v2/MeiTuan/AddOrder", Loginfo = info, OPTime = DateTime.Now, Type = 2 }).ConfigureAwait(false);
                            //errlist.Add(info);
                        }
                    } else {
                        var info = $"{shopentity.StoreName}-{shopid},订单号：{data.OrderId},{item.food_name},sku:{item.sku_id},sku不对 ";
                        await _errorLogService.AddAsync<ICasaMielSession>(new Domain.ErrorLog { Url = "/api/v2/MeiTuan/AddOrder", Loginfo = info, OPTime = DateTime.Now, Type = 2 }).ConfigureAwait(false);
                        errlist.Add(info);
                        _logger.Error($"AddOrder:{JsonConvert.SerializeObject(new { code = 999, msg = String.Join(", ", errlist.ToArray()) })}");
                        //   return Ok(new { code = 999, msg = "商品下架" });
                    }
                }
                if (errlist.Count > 0) {
                    return Ok(new { code = 999, msg = string.Join(',', errlist.ToArray()) });
                }
            } else {
                // errlist.Add($"{item.food_name},sku:{item.sku_id},sku不对 ");
                _logger.Error($"AddOrder:{JsonConvert.SerializeObject(ptprice)}");
                return Ok(new { code = 999, msg = "商品下架" });
            }
            if (Orderoriginprice != (data.OriginalPrice - data.ShippingFee - packagingMoney)) {
                _logger.Error($"OrderAddError:一网跟美团价格有出入！");
                return Ok(new { code = 0, msg = "" });
            }
            var ictradeNO = "";
            var billNO = "";
            var discu = Orderoriginprice - orderDiscountMoney;
            var pickuptime = DateTime.Now.AddMinutes(30).ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture);
            if (data.deliveryTime > 0) {
                if (DatetimeUtil.GetFromUnixTime(data.deliveryTime) > DateTime.Now.AddMinutes(10)) {
                    pickuptime = DatetimeUtil.GetFromUnixTime(data.deliveryTime).ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture);
                }
            }

            //var cardlist = await _memberCardService.GetCardListAsyncByMobile<ICasaMielSession>(data.recipientPhone);
            //var _cardno = "";

            //if (cardlist != null && cardlist.Where(c => c.IsBind == true).Count() == 2)
            //{
            //    var vipcard = cardlist.Where(c => c.IsBind == true && c.CardType != "3").SingleOrDefault();
            //    if (vipcard != null)
            //    {
            //        _cardno = vipcard.CardNo;
            //    }
            //}
            var icdto = new IcconsumeReq { Rebate = 0, Shopid = shopid, Pickuptime = pickuptime };
            icdto.Product = new List<IcconsumeReq.IcconsumeProductItem>();
            foreach (var item in details) {
                if (icdto.Product.Find(cw => cw.Pid == item.sku_id) != null) {
                    icdto.Product.Find(cw => cw.Pid == item.sku_id).Count += item.quantity;
                } else {
                    icdto.Product.Add(new IcconsumeReq.IcconsumeProductItem { Pid = item.sku_id, Count = item.quantity, Pname = "" });
                }

            }

            var icentity = await _icApiService.ThirdOrder(icdto).ConfigureAwait(false);
            _logger.Trace($"thirdorder，Result:{JsonConvert.SerializeObject(icentity)}，req：{JsonConvert.SerializeObject(icdto)}");
            if (icentity.code == 0) {
                var jobject = JsonConvert.DeserializeObject<JObject>(icentity.content);
                ictradeNO = jobject["tradeno"].ToString();
                billNO = jobject["billno"].ToString();
                data.IcTradeNo = ictradeNO;
                data.BillNo = billNO;
            } else {
                return Ok(icentity);
            }


            try {

                var pay = new IcConsumepayReq {
                    Phoneno = data.RecipientPhone,
                    Shopid = shopid,
                    Tradeno = ictradeNO,
                    Createinvoice = true
                };
                pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>
                {
                        new IcConsumepayReq.PaycontentItem
                        {
                            Paytype = "12",
                            Paymoney = data.OriginalPrice.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                            Paytradeno = $"{data.OrderId}C{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}"
                        }
                    };
                pay.Payfee = new List<IcConsumepayReq.PayfeeItem>();
                if (shippingFee > 0) {
                    pay.Payfee.Add(new IcConsumepayReq.PayfeeItem { Feetype = "1", Fee = shippingFee.ToString(CultureInfo.CurrentCulture).ToDouble(0), Description = "配送费" });//配送费
                }
                if (packagingMoney > 0) {
                    pay.Payfee.Add(new IcConsumepayReq.PayfeeItem { Feetype = "2", Fee = packagingMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0), Description = "包装费" });//包装费
                }

                if (orderDiscountMoney > 0) {
                    pay.Payfee.Add(new IcConsumepayReq.PayfeeItem { Feetype = "3", Fee = orderDiscountMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0), Description = "第三方平台积分抵扣金额" });//第三方平台抵扣金额 
                }
                //if (data.orderDiscountMoney > 0)
                //{
                //    pay.payfee.Add(new IcConsumepayDto.Payfee { feetype = "3", fee = data.orderDiscountMoney.ToDouble(0) / 100, description = "优惠券" });//第三方平台抵金额 
                //}

                var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
                _logger.Trace($"icconsumepay，Result:{JsonConvert.SerializeObject(zmodel)}，req：{JsonConvert.SerializeObject(pay)}");
                if (zmodel.code == 0) {
                    var jobject = JsonConvert.DeserializeObject<JObject>(zmodel.content);
                    if (jobject != null && jobject["invoiceqrcode"] != null) {
                        data.InvoiceUrl = jobject["invoiceqrcode"].ToString();
                        // await _order.UpdateOrderInvoiceUrlByOrderCodeAsync<ICasaMielSession>(data.OrderId.ToString(CultureInfo.CurrentCulture), invoiceUrl).ConfigureAwait(false);
                    }
                    var result = await _storeApiService.AddMtOrderV2Async(data).ConfigureAwait(false);
                    _logger.Trace($"AddMtOrder:{JsonConvert.SerializeObject(result)}");
                    //var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
                    // if (dynamicdata["ResultNo"].ToString() == "00000000")
                    if (result.Code == 0) {

                        //var order = await _order.GetByOrderCodeAsync<ICasaMielSession>(data.OrderId.ToString(CultureInfo.CurrentCulture)).ConfigureAwait(false);
                        //try {
                        //    using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                        //        var noticEntity = new NoticeBaseEntity() {
                        //            RemindTime = DateTime.Now.AddMinutes(-3),
                        //            CreateTime = DateTime.Now,
                        //            RelationId = order.OrderBaseId,
                        //            StoreId = order.StoreId,
                        //            NoticeType = 0
                        //        };
                        //        await _notice.AddAsync(noticEntity, uow).ConfigureAwait(false);
                        //    }
                        //} catch (SqlException ex) {
                        //    await _memcachedClient.RemoveAsync(_cachekey).ConfigureAwait(false);

                        //    _logger.Error($"addNotice:{ex.StackTrace}");
                        //}
                        return Ok(new { code = 0, msg = "" });
                    } else {
                        var req = new ThirdOrderBackReq { Tradeno = ictradeNO };
                        var d = await _icApiService.ThirdOrderBack(req).ConfigureAwait(false);
                        _logger.Trace($"thirdorderback,req:{JsonConvert.SerializeObject(req)},result:{JsonConvert.SerializeObject(d)}");
                        if (d.code == 0) {
                            await _order.DeleteAsync<ICasaMielSession>($"{data.OrderId}").ConfigureAwait(false);
                            var r = await _storeApiService.OrderDelete(data.OrderId.ToString(CultureInfo.CurrentCulture)).ConfigureAwait(false);
                            _logger.Trace($"OrderDelete:{data.OrderId}");
                        }
                        await _memcachedClient.RemoveAsync(_cachekey).ConfigureAwait(false);
                        var info = $"{shopentity.StoreName}-{shopid},订单号：{data.OrderId}, remark:{zmodel},req:{JsonConvert.SerializeObject(data)}";
                        await _errorLogService.AddAsync<ICasaMielSession>(new Domain.ErrorLog { Url = "/api/v2/MeiTuan/AddOrder", Loginfo = info, OPTime = DateTime.Now, Type = 2 }).ConfigureAwait(false);

                        return Ok(d);
                    }

                } else {
                    var info = $"{shopentity.StoreName}-{shopid},订单号：{data.OrderId}, remark:{zmodel},req:{JsonConvert.SerializeObject(data)}";
                    await _errorLogService.AddAsync<ICasaMielSession>(new Domain.ErrorLog { Url = "/api/v2/MeiTuan/AddOrder", Loginfo = info, OPTime = DateTime.Now, Type = 2 }).ConfigureAwait(false);

                    var req = new ThirdOrderBackReq { Tradeno = ictradeNO };
                    var d = await _icApiService.ThirdOrderBack(req).ConfigureAwait(false);
                    _logger.Trace($"thirdorderback,req:{JsonConvert.SerializeObject(req)},result:{JsonConvert.SerializeObject(d)},ResultRemark:{zmodel.msg}");

                    await _memcachedClient.RemoveAsync(_cachekey).ConfigureAwait(false);

                    return Ok(zmodel);
                }
            } catch {
                //  _logger.Error($"AddOrder:{ex.StackTrace}");
                var req = new ThirdOrderBackReq { Tradeno = ictradeNO };
                var d = await _icApiService.ThirdOrderBack(req).ConfigureAwait(false);
                await _order.DeleteAsync<ICasaMielSession>($"{data.OrderId}").ConfigureAwait(false);
                _logger.Trace($"thirdorderback,req:{JsonConvert.SerializeObject(req)},result:{JsonConvert.SerializeObject(d)}");
                await _memcachedClient.RemoveAsync(_cachekey).ConfigureAwait(false);
                throw;
            }

        }

        /// <summary>
        /// 备用
        /// </summary>
        /// <returns>The complate t.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        /// <remarks>{"orderCode":""}</remarks>

        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> OrderComplateT([FromBody] JObject data, [FromHeader(Name = "u-token")] string token)
        {
            _logger.Trace($"OrderComplateT:{JsonConvert.SerializeObject(data)}");
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            if (data == null || data["orderCode"] == null) {
                throw new ArgumentNullException(nameof(data));
            }
            //    var list = await _order.GetList<ICasaMielSession>();
            //    foreach (var item in list)
            //    {
            //        var command = new ThirdOrderPickupCommand(item.OrderCode, 1);
            //        var result1 = await _mediator.Send(command);
            //        if (result1.code == 0)
            //        {
            //            var rsp = await _storeApiService.MeituanComplate2(data["orderCode"].ToString());
            //            _logger.Trace("MeituanComplateT:" + rsp);
            //            var dynamicdata = JsonConvert.DeserializeObject<JObject>(rsp);

            //        }
            //        Thread.Sleep(10);
            //}


            //    return Ok("");
            var command1 = new ThirdOrderPickupCommand(data["orderCode"].ToString(), 1);
            var result = await _mediator.Send(command1).ConfigureAwait(false);
            if (result.code == 0) {
                var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>(data["orderCode"].ToString()).ConfigureAwait(false);
                await _order.OrderOperationLogAddAsync<ICasaMielSession>(new OrderOperationLog {
                    BillType = 3,
                    OrderCode = entity.OrderCode,
                    OrderBaseId = entity.OrderBaseId,
                    Remark = "美团订单手动完成",
                    CreateTime = DateTime.Now
                }).ConfigureAwait(false);
                //var rsp = await _storeApiService.MeituanComplate2V2Async(data["orderCode"].ToString()).ConfigureAwait(false);
                //_logger.Trace($"MeituanComplateT:{JsonConvert.SerializeObject(rsp)}");
                //var dynamicdata = JsonConvert.DeserializeObject<JObject>(rsp);
                //return Ok(rsp);
            }
            return Ok(result);

        }

        /// <summary>
        /// Orders the complate tt.
        /// </summary>
        /// <returns>The complate tt.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        /// <remarks>{"orderId":"","billno":""}</remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> OrderComplateTT([FromBody] JObject data, [FromHeader(Name = "u-token")] string token)
        {
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            if (data == null || data["orderId"] == null) {
                throw new ArgumentNullException(nameof(data));
            }
            var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>(data["orderId"].ToString()).ConfigureAwait(false);
            if (entity == null) {
                return Ok(new { code = 9999, msg = "订单不存在" });
            }

            if (entity.OrderStatus == (int)OrderStatus.Completed) {
                return Ok(new { code = 0, msg = "订单完成" });
            }
            var billno = data["billno"].ToString();
            var s = false;
            using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                entity.ResBillNo = billno;
                entity.OrderStatus = (int)OrderStatus.Completed;
                s = await _order.OrderBaseUPdateAsync(entity, uow).ConfigureAwait(false);
            }
            if (s) {
                await _order.OrderOperationLogAddAsync<ICasaMielSession>(new OrderOperationLog {
                    BillType = 3,
                    OrderCode = entity.OrderCode,
                    OrderBaseId = entity.OrderBaseId,
                    Remark = "美团订单手动完成",
                    CreateTime = DateTime.Now
                }).ConfigureAwait(false);
                // var result = await _storeApiService.MeituanComplate2V2Async(entity.OrderCode).ConfigureAwait(false);

            }
            return Ok(s);

        }
        /// <summary>
        /// Orders the complate.
        /// </summary>
        /// <returns>The complate.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> OrderComplate([FromBody] AddMeiTuanOrderReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            var shopid = data.ePoiId.ToInt32(0);
            var mtentity = await _thirdPartyPlatformConfigService.FindAsync<ICasaMielSession>(shopid).ConfigureAwait(false);
            if (mtentity == null || mtentity.MeiTuanEnable == false) {
                _logger.Trace($"美团ePoiId：{shopid}");
                return Ok(new { code = 0, msg = "还未开通！" });
            }

            _logger.Trace($"OrderComplate:{JsonConvert.SerializeObject(data)}");
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }

            var _cachekey = _memcachedPre + Constant.MEITUANORDERID + data.OrderId.ToString(CultureInfo.CurrentCulture);
            var trynum = _memcachedClient.Increment(_cachekey, 1, 1);

            if (trynum == 1) {
                var command = new ThirdOrderPickupCommand(data.OrderId.ToString(CultureInfo.CurrentCulture), 1);
                var commandResult = await _mediator.Send(command).ConfigureAwait(false);

                if (commandResult.code == 0) {
                    var result = await _storeApiService.MeituanComplateV2Async(data).ConfigureAwait(false);
                    _logger.Trace($"MeituanComplate:{JsonConvert.SerializeObject(result)}");
                    //var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
                    //if (dynamicdata["ResultNo"].ToString() == "00000000")
                    //{
                    //    return Ok(new { code = 0, msg = "" });
                    //}
                    if (result.Code == 0) {
                        return Ok(result);
                    }
                    _memcachedClient.Remove(_cachekey);
                    return Ok(new { code = 9999, msg = result.Msg });
                } else if (commandResult.code == 8888)//订单已完成
                  {
                    var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>(data.OrderId.ToString(CultureInfo.CurrentCulture)).ConfigureAwait(false);

                    await _order.OrderOperationLogAddAsync<ICasaMielSession>(new OrderOperationLog {
                        BillType = 3,
                        OrderCode = entity.OrderCode,
                        OrderBaseId = entity.OrderBaseId,
                        Remark = "美团订单完成",
                        CreateTime = DateTime.Now
                    }).ConfigureAwait(false);
                    return Ok(new { code = 0, msg = "" });
                }
                return Ok(commandResult);
            }
            _memcachedClient.Remove(_cachekey);
            return Ok(new {
                code = 9999,
            });
        }
        /// <summary>
        /// Refund the specified data and token.
        /// </summary>
        /// <returns>The refund.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<string>> Refund([FromBody]MetuanRefundReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            _logger.Trace($"Refund:{JsonConvert.SerializeObject(data)}");
            if (token != _apitoken) {
                return new BaseResult<string>("", 9999, "token无效");
            }
            if (data.NotifyType == "agree") {
                var commamd = new CancelOrderCommand(data.OrderId.ToString(CultureInfo.CurrentCulture), 1, "", data.Reason);
                var result1 = await _mediator.Send(commamd).ConfigureAwait(false);
            }
            var result = await _storeApiService.MeituanRefundV2Async(data.NotifyType, data.OrderId, data.Reason).ConfigureAwait(false);
            return result;
            //var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            //if (dynamicdata["ResultNo"].ToString() == "00000000")
            //{
            //    return Ok(new { code = 0, msg = "" });
            //}
            //return Ok(new { code = 9999, msg = dynamicdata["ResultRemark"].ToString() });
        }
        /// <summary>
        ///  手动取消订单
        /// </summary>
        /// <returns>The cancel.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>"
        /// <remarks>{"orderCode":""}</remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> OrderCancelT([FromBody]JObject data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            _logger.Trace($"OrderCancel:{JsonConvert.SerializeObject(data)}");
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>(data["orderCode"].ToString()).ConfigureAwait(false);
            if (entity == null) {
                _logger.Trace($"OrderCancel:订单不存在");
                return Ok(new { code = 0, msg = "订单不存在" });
            }
            //var cardlist = await _memberCardService.GetListAsync<ICasaMielSession>(entity.ContactPhone).ConfigureAwait(false);
            //var _cardno = "";

            //if (cardlist != null && cardlist.Count(c => c.IsBind == true) == 2) {
            //    var vipcard = cardlist.Where(c => c.IsBind == true && c.CardType != "3").SingleOrDefault();
            //    if (vipcard != null) {
            //        _cardno = vipcard.CardNO;
            //    }
            //}
            var d = await _icApiService.Icconsumeback(new IcConsumeBackReq { Phoneno = entity.ContactPhone, Tradeno = entity.IcTradeNO }).ConfigureAwait(false);
            if (d.code == 0 || d.code == 205) {
                JObject obj = JsonConvert.DeserializeObject<JObject>(d.content);
                _logger.Trace($"icconsumeback:{d.content}");

                _logger.Trace($"OrderCode:{entity.OrderCode},tradeno_origin:{obj["tradeno_origin"].ToString()},tradeno:{obj["tradeno"].ToString()},");
                var billno = obj["tradeno"].ToString();
                entity.OrderStatus = (int)OrderStatus.Cancelled;
                entity.ResBillNo = billno;
                using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                    var s = await _order.OrderBaseUPdateAsync(entity, uow).ConfigureAwait(false);
                }
            }
            return Ok(d);

        }
        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> OrderCancel([FromBody]MetuanOrderCancelReq data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            _logger.Trace($"OrderCancel:{JsonConvert.SerializeObject(data)}");
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            var commamd = new CancelOrderCommand(data.OrderId.ToString(CultureInfo.CurrentCulture), 1, data.ReasonCode, data.Reason);
            var result = await _mediator.Send(commamd).ConfigureAwait(false);
            return Ok(result);

        }

        /// <summary>
        /// Changes the express status.
        /// </summary>
        /// <returns>The express status.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        /// <remarks>
        /// { "dispatcherMobile":"13466645645", "dispatcherName":"包晓明", "orderId":2450000102, "shippingStatus":40,"time":1477913825}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> ChangeExpressStatus([FromBody]ChangeExpressStatusRequest data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            _logger.Trace($"ChangeExpressStatus:{JsonConvert.SerializeObject(data)}");

            // logger.Trace($"dispatcherName:{HttpUtility.UrlDecode(data["dispatcherName"].ToString())}");  
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            BaseResult<string> result = await NewMethod1(data).ConfigureAwait(false);
            var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>($"{data.OrderId}").ConfigureAwait(false);
            if (entity == null && data.ShippingStatus>0) {
                var Orderview = await GetOrderView($"{data.OrderId}").ConfigureAwait(false);
                if (Orderview != null) {
                    var shopid = Orderview.Data.EPoiId.ToInt32(0);

                    var mtentity = await _thirdPartyPlatformConfigService.FindAsync<ICasaMielSession>(shopid).ConfigureAwait(false);
                    if (mtentity == null || mtentity.MeiTuanEnable == false) {
                        _logger.Trace($"美团ePoiId：{shopid}");
                        return Ok(new { code = 0, msg = "还未开通！" });
                    }
                    var shopentity = await _storeService.GetByRelationIdAsync<ICasaMielSession>(shopid).ConfigureAwait(false);
                    if (shopentity == null) {
                        _logger.Trace($"门店不存在，美团ePoiId：{shopid}");
                        return Ok(new { code = 0, msg = "门店不存在！" });
                    }
                    var addOrderReq = JsonConvert.DeserializeObject<AddMeiTuanOrderReq>(JsonConvert.SerializeObject(Orderview.Data));

                    //if (string.IsNullOrEmpty(addOrderReq.logisticsDispatcherMobile)) {
                    //    addOrderReq.logisticsDispatcherMobile = "0";
                    //}
                    List<GoodsDetail> details1 = JsonConvert.DeserializeObject<List<GoodsDetail>>(addOrderReq.detail);
                    var details = details1.Where(c => c.sku_id != "1").ToList();

                    var goodslist = new List<GoodsDetailExt>();
                    foreach (var item in details) {
                        var goods = new GoodsDetailExt {
                            app_food_code = item.App_food_code,
                            box_num = Convert.ToInt32(decimal.Truncate(item.Box_num)),
                            cart_id = item.cart_id,
                            box_price = item.box_price,
                            foodShareFeeChargeByPoi = item.foodShareFeeChargeByPoi,
                            food_discount = item.food_discount,
                            food_name = item.food_name,
                            food_property = item.food_property,
                            price = item.price,
                            quantity = item.quantity,
                            sku_id = item.sku_id,
                            unit = item.unit

                        };
                        goodslist.Add(goods);
                    }
                    addOrderReq.detail = JsonConvert.SerializeObject(goodslist);

                    //优惠券
                    var extrasDetails = JsonConvert.DeserializeObject<List<ExtrasDetail>>(addOrderReq.extras);
                    var orderentity = await _order.GetByOrderCodeAsync<ICasaMielSession>(addOrderReq.OrderId.ToString(CultureInfo.CurrentCulture)).ConfigureAwait(false);
                    if (orderentity != null) {
                          return Ok(result);
                    }

                     

                    var drinkcmd = new GetDrinksGoodsIdsCommand();
                    var blacklist = await _mediator.Send(drinkcmd).ConfigureAwait(false);
                    var packagingMoney = 0m;//包装费
                    var orderDiscountMoney = 0;//data.originalPrice - data.total- data.shippingFee;//折扣
                    var Orderoriginprice = 0m;//原价
                    var shippingFee = addOrderReq.ShippingFee;//运费
                    var ptprice = new IcPriceReq { Shopid = shopid, Product = new List<ProductItemReq>() };

                    var errlist = new List<string>();
                    foreach (var item in details) {
                        if (item.sku_id.ToInt32(0) == 0) {
                            //errlist.Add($"{item.food_name},sku不存在 ");
                            var info = $"{shopentity.StoreName}-{shopid},订单号：{addOrderReq.OrderId},{item.food_name},sku不存在";
                            await _errorLogService.AddAsync<ICasaMielSession>(new Domain.ErrorLog { Url = "/api/v2/MeiTuan/AddOrder", Loginfo = info, OPTime = DateTime.Now, Type = 2 }).ConfigureAwait(false);
                            errlist.Add(info);
                        }

                        // packagingMoney += item.box_num * item.box_price;
                        ptprice.Product.Add(new ProductItemReq { Pid = item.sku_id, Count = item.quantity });
                    }
                    packagingMoney += details.Sum(x => x.Box_num * x.box_price);
                    if (errlist.Count > 0) {
                        _logger.Error($"AddOrder:{JsonConvert.SerializeObject(new { code = 999, msg = String.Join(", ", errlist.ToArray()) })}");
                        return Ok(new { code = 999, msg = String.Join(", ", errlist.ToArray()) });
                    }
                    var pzmodel = await _icApiService.Icprice(ptprice).ConfigureAwait(false);
                    if (pzmodel.Product.Count > 0) {
                        foreach (var item in details) {
                            var iteminfo = pzmodel.Product.Find(cw => cw.Pid == item.sku_id);
                            if (iteminfo != null) {
                                var total = iteminfo.Originprice * item.quantity;
                                Orderoriginprice += total;
                                if (blacklist.Contains(item.sku_id)) {
                                    continue;
                                }
                                var goods = await _storeService.GetDetailV2ByReleationIdAsync<ICasaMielSession>(iteminfo.Pid.ToInt32(0)).ConfigureAwait(false);
                                if (goods == null) {
                                    var info = $"{shopentity.StoreName}-{shopid},订单号：{addOrderReq.OrderId},{item.food_name},sku:{item.sku_id},后台系统没产品信息";
                                    await _errorLogService.AddAsync<ICasaMielSession>(new Domain.ErrorLog { Url = "/api/v2/MeiTuan/AddOrder", Loginfo = info, OPTime = DateTime.Now, Type = 2 }).ConfigureAwait(false);
                                    errlist.Add(info);
                                }
                                if (iteminfo.Icprice != item.price) {
                                    var info = $"{shopentity.StoreName}-{shopid},订单号：{addOrderReq.OrderId},sku:{item.sku_id},{item.food_name},价格:{item.price},一网价格{iteminfo.Icprice}{iteminfo.Pname},sku{iteminfo.Pid}";
                                    await _errorLogService.AddAsync<ICasaMielSession>(new Domain.ErrorLog { Url = "/api/v2/MeiTuan/AddOrder", Loginfo = info, OPTime = DateTime.Now, Type = 2 }).ConfigureAwait(false);
                                    //errlist.Add(info);
                                }
                            } else {
                                var info = $"{shopentity.StoreName}-{shopid},订单号：{addOrderReq.OrderId},{item.food_name},sku:{item.sku_id},sku不对 ";
                                await _errorLogService.AddAsync<ICasaMielSession>(new Domain.ErrorLog { Url = "/api/v2/MeiTuan/AddOrder", Loginfo = info, OPTime = DateTime.Now, Type = 2 }).ConfigureAwait(false);
                                errlist.Add(info);
                                _logger.Error($"AddOrder:{JsonConvert.SerializeObject(new { code = 999, msg = String.Join(", ", errlist.ToArray()) })}");
                                //   return Ok(new { code = 999, msg = "商品下架" });
                            }
                        }
                        if (errlist.Count > 0) {
                            return Ok(new { code = 999, msg = string.Join(',', errlist.ToArray()) });
                        }
                    } else {
                        // errlist.Add($"{item.food_name},sku:{item.sku_id},sku不对 ");
                        _logger.Error($"AddOrder:{JsonConvert.SerializeObject(ptprice)}");
                        return Ok(new { code = 999, msg = "商品下架" });
                    }
                    if (Orderoriginprice != (addOrderReq.OriginalPrice - addOrderReq.ShippingFee - packagingMoney)) {
                        _logger.Error($"OrderAddError:一网跟美团价格有出入！");
                        return Ok(new { code = 0, msg = "" });
                    }
                    var ictradeNO = "";
                    var billNO = "";
                    var discu = Orderoriginprice - orderDiscountMoney;
                    var pickuptime = DateTime.Now.AddMinutes(30).ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture);
                    if (addOrderReq.deliveryTime > 0) {
                        pickuptime = DatetimeUtil.GetFromUnixTime(addOrderReq.deliveryTime).ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture);
                    }

                    //var cardlist = await _memberCardService.GetCardListAsyncByMobile<ICasaMielSession>(data.recipientPhone);
                    //var _cardno = "";

                    //if (cardlist != null && cardlist.Where(c => c.IsBind == true).Count() == 2)
                    //{
                    //    var vipcard = cardlist.Where(c => c.IsBind == true && c.CardType != "3").SingleOrDefault();
                    //    if (vipcard != null)
                    //    {
                    //        _cardno = vipcard.CardNo;
                    //    }
                    //}
                    var icdto = new IcconsumeReq { Rebate = 0, Shopid = shopid, Pickuptime = pickuptime };
                    icdto.Product = new List<IcconsumeReq.IcconsumeProductItem>();
                    foreach (var item in details) {
                        if (icdto.Product.Find(cw => cw.Pid == item.sku_id) != null) {
                            icdto.Product.Find(cw => cw.Pid == item.sku_id).Count += item.quantity;
                        } else {
                            icdto.Product.Add(new IcconsumeReq.IcconsumeProductItem { Pid = item.sku_id, Count = item.quantity, Pname = "" });
                        }

                    }
                    orderentity = await _order.GetByOrderCodeAsync<ICasaMielSession>(addOrderReq.OrderId.ToString(CultureInfo.CurrentCulture)).ConfigureAwait(false);
                    if (orderentity!=null){
                         
                        return Ok(result);
                    }

                   
                    var icentity = await _icApiService.ThirdOrder(icdto).ConfigureAwait(false);
                    _logger.Trace($"thirdorder，Result:{JsonConvert.SerializeObject(icentity)}，req：{JsonConvert.SerializeObject(icdto)}");
                    if (icentity.code == 0) {
                        var jobject = JsonConvert.DeserializeObject<JObject>(icentity.content);
                        ictradeNO = jobject["tradeno"].ToString();
                        billNO = jobject["billno"].ToString();
                        addOrderReq.IcTradeNo = ictradeNO;
                        addOrderReq.BillNo = billNO;
                    } else {
                        return Ok(icentity);
                    }


                    try {

                        var pay = new IcConsumepayReq {
                            Phoneno = addOrderReq.RecipientPhone,
                            Shopid = shopid,
                            Tradeno = ictradeNO,
                            Createinvoice = true
                        };
                        pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>
                        {
                                new IcConsumepayReq.PaycontentItem
                                {
                                    Paytype = "12",
                                    Paymoney = addOrderReq.OriginalPrice.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                                    Paytradeno = $"{addOrderReq.OrderId}C{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}"
                                }
                            };
                        pay.Payfee = new List<IcConsumepayReq.PayfeeItem>();
                        if (shippingFee > 0) {
                            pay.Payfee.Add(new IcConsumepayReq.PayfeeItem { Feetype = "1", Fee = shippingFee.ToString(CultureInfo.CurrentCulture).ToDouble(0), Description = "配送费" });//配送费
                        }
                        if (packagingMoney > 0) {
                            pay.Payfee.Add(new IcConsumepayReq.PayfeeItem { Feetype = "2", Fee = packagingMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0), Description = "包装费" });//包装费
                        }

                        if (orderDiscountMoney > 0) {
                            pay.Payfee.Add(new IcConsumepayReq.PayfeeItem { Feetype = "3", Fee = orderDiscountMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0), Description = "第三方平台积分抵扣金额" });//第三方平台抵扣金额 
                        }
                        //if (data.orderDiscountMoney > 0)
                        //{
                        //    pay.payfee.Add(new IcConsumepayDto.Payfee { feetype = "3", fee = data.orderDiscountMoney.ToDouble(0) / 100, description = "优惠券" });//第三方平台抵金额 
                        //}

                        var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
                        _logger.Trace($"icconsumepay，Result:{JsonConvert.SerializeObject(zmodel)}，req：{JsonConvert.SerializeObject(pay)}");
                        if (zmodel.code == 0) {
                            var jobject = JsonConvert.DeserializeObject<JObject>(zmodel.content);
                            if (jobject != null && jobject["invoiceqrcode"] != null) {
                                addOrderReq.InvoiceUrl = jobject["invoiceqrcode"].ToString();
                            }
                        } else {
                            var req = new ThirdOrderBackReq { Tradeno = ictradeNO };
                            var d = await _icApiService.ThirdOrderBack(req).ConfigureAwait(false);
                            _logger.Trace($"thirdorderback,req:{JsonConvert.SerializeObject(req)},result:{JsonConvert.SerializeObject(d)}");

                            return Ok(d);
                        }


                        var result1 = await _storeApiService.AddMtOrderV2Async(addOrderReq).ConfigureAwait(false);
                        _logger.Trace($"AddrAddMtOrder:{JsonConvert.SerializeObject(result1)}");
                        // var dynamicdatas = JsonConvert.DeserializeObject<JObject>(result1);
                        if (result1.Code == 0) {
                            //var order = await _order.GetByOrderCodeAsync<ICasaMielSession>($"{addOrderReq.OrderId}").ConfigureAwait(false);
                            //using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                            //    var noticEntity = new NoticeBaseEntity() {
                            //        RemindTime = DateTime.Now.AddMinutes(-3),
                            //        CreateTime = DateTime.Now,
                            //        RelationId = order.OrderBaseId,
                            //        StoreId = order.StoreId,
                            //        NoticeType = 0
                            //    };
                            //    await _notice.AddAsync(noticEntity, uow).ConfigureAwait(false);
                            //}
                            await NewMethod1(data).ConfigureAwait(false);
                            return Ok(new { code = 0, msg = "" });
                        } else {
                            var info = $"{shopentity.StoreName}-{shopid},订单号：{addOrderReq.OrderId}, remark:{result1.Msg},req:{JsonConvert.SerializeObject(data)}";
                            await _errorLogService.AddAsync<ICasaMielSession>(new Domain.ErrorLog { Url = "/api/v2/MeiTuan/AddOrder", Loginfo = info, OPTime = DateTime.Now, Type = 2 }).ConfigureAwait(false);

                            var req = new ThirdOrderBackReq { Tradeno = ictradeNO };
                            var d = await _icApiService.ThirdOrderBack(req).ConfigureAwait(false);
                            _logger.Trace($"thirdorderback,req:{JsonConvert.SerializeObject(req)},result:{JsonConvert.SerializeObject(d)},ResultRemark:{result1.Msg}");
                            return Ok(new { code = 9999, msg = result1.Msg });
                        }
                    } catch {

                        var req = new ThirdOrderBackReq { Tradeno = ictradeNO };
                        var d = await _icApiService.ThirdOrderBack(req).ConfigureAwait(false);
                        _logger.Trace($"thirdorderback,req:{JsonConvert.SerializeObject(req)},result:{JsonConvert.SerializeObject(d)}");
                        throw;
                    }
                }

                _logger.Trace($"ChangeExpressStatus:订单不存在");
                return Ok(new { code = 0, msg = "" });
            }
            
            return Ok(result);
        }

        private async Task<BaseResult<string>> NewMethod1(ChangeExpressStatusRequest data)
        {
            var dispatcherName = HttpUtility.UrlDecode(data.DispatcherName);
            var begin = DatetimeUtil.GetUnixTime(DateTime.Now, Common.TimePrecision.Millisecond);
            var result = await _storeApiService.MeituanChangeExpressStatusV2Async(data.DispatcherMobile, dispatcherName, data.OrderId, data.ShippingStatus, data.Time).ConfigureAwait(false);
            var endExc = DatetimeUtil.GetUnixTime(DateTime.Now, Common.TimePrecision.Millisecond);

            _logger.Trace($"ChangeExpressStatus:{JsonConvert.SerializeObject(result)},执行时间：{endExc - begin}毫秒");
            return result;
        }

        private async Task UpdateStock(ThirdPartyPlatformConfig item)
        {
            var source = 0;
            if (_apiname == "hgspApi") {
                source = 1;
            }
            var data = new { epoiId = item.ShopId, source };
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/dish/UpdateStockByEpoiId") {
                Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")
            };
            requestMessage.Headers.Add("u-token", "dsbqe1236e056f23f83e71dA");
            var client = _httpClientFactory.CreateClient("MentuanOpen");
            var response = await client.SendAsync(requestMessage).ConfigureAwait(false);
            if (response.IsSuccessStatusCode) {
                var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                _stocklogger.Trace($"{ item.ShopId},{result}");
            } else {
                _stocklogger.Error($"{ item.ShopId},{ response.StatusCode}");
            }
        }
        private async Task MappingProduct(ThirdPartyPlatformConfig item)
        {
            try {

                var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"api/MeiTuanAPI/JBP_OrderAPI/meituan_mapping?ePoiId={item.ShopId}");
                var client = _httpClientFactory.CreateClient("JdOpenApi");

                var response = await client.SendAsync(requestMessage).ConfigureAwait(false);
                if (response.IsSuccessStatusCode) {
                    var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    _stocklogger.Trace(result);
                } else {
                    _stocklogger.Error($"meituan_mapping:{ item.ShopId}{item.ShopName},{ response.StatusCode}");
                }
            } catch (System.Net.Sockets.SocketException ex) {
                _stocklogger.Error($"meituan_mapping:{ item.ShopId},{ ex.StackTrace}");
            } catch (TaskCanceledException ex) {
                _stocklogger.Error($"meituan_mapping:{ item.ShopId},{ ex.StackTrace}");

            }
        }
        /// <summary>
        /// Doproduct this instance.
        /// </summary>
        /// <returns>The doproduct.</returns>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> Doproduct()
        {
            var begin = DatetimeUtil.GetUnixTime(DateTime.Now, TimePrecision.Millisecond);
            var listall = await _thirdPartyPlatformConfigService.GetAllAsync<ICasaMielSession>().ConfigureAwait(false);
            var list = listall.Where(c => c.MeiTuanEnable == true).ToList();


            int pagesize = Math.Ceiling(Convert.ToDecimal(list.Count) / 4).ToString(CultureInfo.CurrentCulture).ToInt32(0);
            //   await Task.Run(async () =>
            //{

            var backgroundTasks = new[]
            {
                Task.Run(async () =>
                {

                    var t = list.Skip(0).Take(pagesize);
                foreach (var item in t)
                {

                    await MappingProduct(item).ConfigureAwait(false);
                    await NewMethod(item);
                        await UpdateStock(item).ConfigureAwait(false);
                }
                return "task";
            }),
                Task.Run(async()=>
            { var t = list.Skip(pagesize).Take(pagesize);
            foreach (var item in t)
            {
                    await MappingProduct(item).ConfigureAwait(false);
                    await NewMethod(item);
                    await UpdateStock(item).ConfigureAwait(false);
            }
            return "task1";
        }),
                Task.Run(async () =>
                {

            var t = list.Skip(2 * pagesize).Take(pagesize);
                foreach (var item in t)
                {
                        await MappingProduct(item).ConfigureAwait(false);
                        await NewMethod(item);
                        await UpdateStock(item).ConfigureAwait(false);
                }
                return "task2";
            }),
                 Task.Run(async () =>
                {

                var t = list.Skip(3* pagesize).Take(pagesize);
                foreach (var item in t)
                {
                       await MappingProduct(item).ConfigureAwait(false);
                     await NewMethod(item);
await UpdateStock(item).ConfigureAwait(false);
                    }
                return "task3";
                })

            };

            try {
                var completedTask = await Task.WhenAll(backgroundTasks).ConfigureAwait(true);
                var result = completedTask;
                _stocklogger.Trace($"{string.Join(',', result)}");
                var end = DatetimeUtil.GetUnixTime(DateTime.Now, TimePrecision.Millisecond);
                _stocklogger.Trace($"ComplateTask,执行时间{end - begin}毫秒");
            } catch (AggregateException ex) {
                foreach (var item in ex.InnerExceptions) {
                    _stocklogger.Error(string.Format(CultureInfo.CurrentCulture, "异常类型：{0}{1}来自：  {2} {3} 异常内容：{4}", item.GetType(),
                Environment.NewLine, item.Source,
                Environment.NewLine, item.Message));

                }

            }
            //await  Task.WhenAll(task,task1, task2).ContinueWith(p =>
            //{

            //    var end = DatetimeUtil.GetUnixTime(DateTime.Now, TimePrecision.Millisecond);
            //    _stocklogger.Trace($"ComplateTask,执行时间{end - begin}毫秒");
            //}, TaskContinuationOptions.OnlyOnRanToCompletion);

            //   await Task.WhenAll(task, task1, task2);


            return Ok($"ComplateTask");
            #region MyRegion
            /* Parallel.Invoke(async () =>
             {
                 var t = list.Skip(0).Take(pagesize);
                 foreach (var item in t)
                 {
                     var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"api/MeiTuanAPI/JBP_OrderAPI/meituan_mapping?ePoiId={item.ShopId}");
                     var client = _httpClientFactory.CreateClient("JdOpenApi");
                     var response = await client.SendAsync(requestMessage);
                     if (response.IsSuccessStatusCode)
                     {
                         var result = await response.Content.ReadAsStringAsync();
                         _stocklogger.Trace(result);
                     }
                   else{

                   }
                 }

             }, async () =>
             {
                 var t = list.Skip(pagesize).Take(pagesize);
                 foreach (var item in t)
                 {
                     var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"api/MeiTuanAPI/JBP_OrderAPI/meituan_mapping?ePoiId={item.ShopId}");
                     var client = _httpClientFactory.CreateClient("JdOpenApi");
                     var response = await client.SendAsync(requestMessage);
                     if (response.IsSuccessStatusCode)
                     {
                         var result = await response.Content.ReadAsStringAsync();
                         _stocklogger.Trace(result);
                     }
                 }
             }, async () =>
             {
                 var t = list.Skip(pagesize * 2).Take(pagesize);
                 foreach (var item in t)
                 {
                     var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"api/MeiTuanAPI/JBP_OrderAPI/meituan_mapping?ePoiId={item.ShopId}");
                     var client = _httpClientFactory.CreateClient("JdOpenApi");
                     var response = await client.SendAsync(requestMessage);
                     if (response.IsSuccessStatusCode)
                     {
                         var result = await response.Content.ReadAsStringAsync();
                         _stocklogger.Trace(result);
                     }
                 }
             }, async () =>
             {
                 var t = list.Skip(pagesize * 3).Take(pagesize);
                 foreach (var item in t)
                 {
                     var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"api/MeiTuanAPI/JBP_OrderAPI/meituan_mapping?ePoiId={item.ShopId}");
                     var client = _httpClientFactory.CreateClient("JdOpenApi");
                     var response = await client.SendAsync(requestMessage);
                     if (response.IsSuccessStatusCode)
                     {
                         var result = await response.Content.ReadAsStringAsync();
                         _stocklogger.Trace(result);
                     }
                 }
             });

           return Ok("");
           */
            #endregion

        }
        /// <summary>
        /// Setproduct this instance.
        /// </summary>
        /// <returns>The setproduct.</returns>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> Setproduct()
        {
            var listAll = await _thirdPartyPlatformConfigService.GetAllAsync<ICasaMielSession>().ConfigureAwait(false);
            var list = listAll.Where(c => c.MeiTuanEnable == true).ToList();
            foreach (var l in list) {
                await NewMethod(l);

            }

            return Ok("");
        }

        private async Task NewMethod(ThirdPartyPlatformConfig l)
        {
            var source = 0;
            if (_apiname == "hgspApi") {
                source = 1;
            }
            try {
                var data = new { ePoiId = l.ShopId.ToString(CultureInfo.CurrentCulture), source };
                using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/dish/GetqueryBaseListByEPoiId") {
                    Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")
                }) {
                    requestMessage.Headers.Add("u-token", _apitoken);

                    var client = _httpClientFactory.CreateClient("MentuanOpen");
                    using (
                    var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
                        if (response.IsSuccessStatusCode) {
                            var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                            JObject jObject = JsonConvert.DeserializeObject<JObject>(result);
                            _stocklogger.Trace(jObject);
                        }
                    }
                }
            } catch (System.Net.Sockets.SocketException ex) {
                _stocklogger.Error($"{l.ShopId},{ex.StackTrace}");
            } catch (TaskCanceledException ex) {
                _stocklogger.Error($"{l.ShopId},{ex.StackTrace}");
            }
        }

        /// <summary>
        /// Kucun this instance.
        /// </summary>
        /// <returns>The kucun.</returns>
        [Route("[Action]")]
        [HttpGet]
        public async Task<IActionResult> Kucun()
        {
            if (DateTime.Now.Hour > 23) {
                return Ok("");
            }
            if (DateTime.Now.Hour < 7) {
                return Ok("");
            }
            var listAll = await _thirdPartyPlatformConfigService.GetAllAsync<ICasaMielSession>().ConfigureAwait(false);
            var list = listAll.Where(c => c.MeiTuanEnable == true).ToList();
            Parallel.Invoke(async () => {
                var t = list.Skip(0).Take(6);
                foreach (var item in t) {
                    var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"api/OpendjAPI/StockAPI/meituan_updateStockbyePoiId?ePoiId={item.ShopId}");
                    var client = _httpClientFactory.CreateClient("JdOpenApi");
                    var response = await client.SendAsync(requestMessage).ConfigureAwait(false);
                    if (response.IsSuccessStatusCode) {
                        var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        _stocklogger.Trace(result);
                    }
                }

            }, async () => {
                var t = list.Skip(6).Take(6);
                foreach (var item in t) {
                    var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"api/OpendjAPI/StockAPI/meituan_updateStockbyePoiId?ePoiId={item.ShopId}");
                    var client = _httpClientFactory.CreateClient("JdOpenApi");
                    var response = await client.SendAsync(requestMessage).ConfigureAwait(false);
                    if (response.IsSuccessStatusCode) {
                        var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        _stocklogger.Trace(result);
                    }
                }
            }, async () => {
                var t = list.Skip(12).Take(6);
                foreach (var item in t) {
                    var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"api/OpendjAPI/StockAPI/meituan_updateStockbyePoiId?ePoiId={item.ShopId}");
                    var client = _httpClientFactory.CreateClient("JdOpenApi");
                    var response = await client.SendAsync(requestMessage).ConfigureAwait(false);
                    if (response.IsSuccessStatusCode) {
                        var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        _stocklogger.Trace(result);
                    }
                }
            }, async () => {
                var t = list.Skip(18).Take(6);
                foreach (var item in t) {
                    var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"api/OpendjAPI/StockAPI/meituan_updateStockbyePoiId?ePoiId={item.ShopId}");
                    var client = _httpClientFactory.CreateClient("JdOpenApi");
                    var response = await client.SendAsync(requestMessage).ConfigureAwait(false);
                    if (response.IsSuccessStatusCode) {
                        var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        _stocklogger.Trace(result);
                    }
                }
            });
            return Ok("");
        }
        /// <summary>
        /// Kucun this instance.
        /// </summary>
        /// <returns>The kucun.</returns>
        [Route("[Action]")]
        [HttpGet]
        public async Task<IActionResult> Kucun2()
        {
            if (DateTime.Now.Hour > 23) {
                return Ok("");
            }
            if (DateTime.Now.Hour < 6) {
                return Ok("");
            }
            var source = 0;

            if (_apiname == "hgspApi") {
                source = 1;
            }
            var listAll = await _thirdPartyPlatformConfigService.GetAllAsync<ICasaMielSession>().ConfigureAwait(false);
            var list = listAll.Where(c => c.MeiTuanEnable == true).ToList();
            Task task = new Task(async () => {
                foreach (var item in list) {
                    var data = new { epoiId = item.ShopId, source };
                    var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/dish/UpdateStockByEpoiId") {
                        Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")
                    };
                    requestMessage.Headers.Add("u-token", "dsbqe1236e056f23f83e71dA");
                    var client = _httpClientFactory.CreateClient("MentuanOpen");
                    var response = await client.SendAsync(requestMessage).ConfigureAwait(false);
                    if (response.IsSuccessStatusCode) {
                        var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        _stocklogger.Trace($"{ item.ShopId},{result}");
                    } else {
                        _stocklogger.Error($"{ item.ShopId},{ response.StatusCode}");
                    }
                }
            });
            task.Start();




            return Ok("");
            #region MyRegion
            /*
            int pagesize = Math.Ceiling(Convert.ToDecimal(list.Count) / 4).ToString().ToInt32(0);
            Parallel.Invoke(async () =>
            {
                var t = list.Skip(0).Take(pagesize);
                foreach (var item in t)
                {
                    var data = new { epoiId = item.ShopId };
                    var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/dish/UpdateStockByEpoiId");
                    requestMessage.Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json");
                    requestMessage.Headers.Add("u-token", "dsbqe1236e056f23f83e71dA");
                    var client = _httpClientFactory.CreateClient("MentuanOpen");
                    var response = await client.SendAsync(requestMessage);
                    if (response.IsSuccessStatusCode)
                    {
                        var result = await response.Content.ReadAsStringAsync();
                        _stocklogger.Trace($"{ item.ShopId},{result}");
                    }
                    else
                    {ChangeExpressStatus
                        _stocklogger.Error($"{ item.ShopId},{ response.StatusCode}");
                    }
                }

            }, async () =>
            {
                var t = list.Skip(pagesize).Take(pagesize);
                foreach (var item in t)
                {
                    var data = new { epoiId = item.ShopId };
                    var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/dish/UpdateStockByEpoiId");
                    requestMessage.Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json");
                    requestMessage.Headers.Add("u-token", "dsbqe1236e056f23f83e71dA");
                    var client = _httpClientFactory.CreateClient("MentuanOpen");
                    var response = await client.SendAsync(requestMessage);
                    if (response.IsSuccessStatusCode)
                    {
                        var result = await response.Content.ReadAsStringAsync();
                        _stocklogger.Trace($"{ item.ShopId},{result}");
                    }
                    else
                    {
                        _stocklogger.Error($"{ item.ShopId},{ response.StatusCode}");
                    }
                }
            }, async () =>
            {
                var t = list.Skip(pagesize * 2).Take(pagesize);
                foreach (var item in t)
                {
                    var data = new { epoiId = item.ShopId };
                    var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/dish/UpdateStockByEpoiId");
                    requestMessage.Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json");
                    requestMessage.Headers.Add("u-token", "dsbqe1236e056f23f83e71dA");
                    var client = _httpClientFactory.CreateClient("MentuanOpen");
                    var response = await client.SendAsync(requestMessage);
                    if (response.IsSuccessStatusCode)
                    {
                        var result = await response.Content.ReadAsStringAsync();
                        _stocklogger.Trace($"{ item.ShopId},{result}");
                    }
                    else
                    {
                        _stocklogger.Error($"{ item.ShopId},{ response.StatusCode}");
                    }
                }
            }, async () =>
            {
                var t = list.Skip(pagesize * 3).Take(pagesize);
                foreach (var item in t)
                {
                    var data = new { epoiId = item.ShopId };
                    var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/dish/UpdateStockByEpoiId");
                    requestMessage.Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json");
                    requestMessage.Headers.Add("u-token", "dsbqe1236e056f23f83e71dA");
                    var client = _httpClientFactory.CreateClient("MentuanOpen");
                    var response = await client.SendAsync(requestMessage);
                    if (response.IsSuccessStatusCode)
                    {
                        var result = await response.Content.ReadAsStringAsync();
                        _stocklogger.Trace($"{ item.ShopId},{result}");
                    }
                    else
                    {
                        _stocklogger.Error($"{ item.ShopId},{ response.StatusCode}");
                    }
                }
            });
            return Ok("");
            */
            #endregion

        }
        /// <summary>
        /// Tradedetail the specified data and token.
        /// </summary>
        /// <returns>The tradedetail.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Tradedetail([FromBody]JObject data, [FromHeader(Name = "u-token")] string token)
        {
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }

            var result = await _storeApiService.MeituanTradedetailV2Async(data).ConfigureAwait(false);
            _logger.Trace($"Tradedetail:{JsonConvert.SerializeObject(data)},result:{result}");
            return Ok(result);
        }

        /// <summary>
        /// Parts the order refund.
        /// </summary>
        /// <returns>The order refund.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public IActionResult PartOrderRefund([FromBody]JObject data, [FromHeader(Name = "u-token")] string token)
        {
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            _logger.Trace($"partOrderRefund:{JsonConvert.SerializeObject(data)}");

            return Ok(new { code = 0, msg = "" });
        }
        /// <summary>
        /// Checkheartbeat this instance.
        /// </summary>
        /// <returns>The checkheartbeat.</returns>
        [HttpPost]
        [Route("[action]")]
        public IActionResult Checkheartbeat()
        {
            return Ok(new { data = "OK" });
        }
        /// <summary>
        /// Adds the third order.
        /// </summary>
        /// <returns>The third order.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> AddThirdOrder(IcconsumeReq req, [FromHeader(Name = "u-token")] string token)
        {
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            var a = await _icApiService.ThirdOrder(req).ConfigureAwait(false);
            return Ok(a);
        }
        /// <summary>
        /// Gets the products by store identifier.
        /// </summary>
        /// <returns>The products by store identifier.</returns>
        /// <param name="storeid">Storeid.</param>
        [HttpGet]
        [Route("[action]")]
        public async Task<IActionResult> GetProductsByStoreId(int storeid)
        {
            var client = _httpClientFactory.CreateClient("JdOpenApi");
            using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"api/MeiTuanAPI/JBP_OrderAPI/queryBaseListByEPoiIdeDishCodenotnull?ePoiId={storeid}")) {
                using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
                    if (response.IsSuccessStatusCode) {
                        var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        var list = JsonConvert.DeserializeObject<List<DishCategory>>(result);
                        var prodlist = new List<WaiMaiDishSkuBasesItem>();
                        foreach (var iten in list) {
                            foreach (var item in iten.waiMaiDishSkuBases) {
                                prodlist.Add(item);
                            }
                        }
                        var q = from p in prodlist

                                group p by p.eDishSkuCode into g
                                where g.Count() > 1
                                select new {
                                    g.Key,

                                };

                        var ttt = from de in prodlist
                                  where (from i in q select i.Key).Contains(de.eDishSkuCode)
                                  select de;
                        return Ok(ttt);
                    }
                }

            }


            return Ok("");
        }

        /// <summary>
        /// Gets the meituan order.
        /// </summary>
        /// <returns>The meituan order.</returns>
        /// <param name="OrdrCode">Ordr code.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetMeituanOrder(string OrdrCode)
        {
            var data = await GetOrderView(OrdrCode).ConfigureAwait(false);
            return Ok(data);
        }


        private async Task<OrderView> GetOrderView(string OrdrCode)
        {
            var ePoiId = "222105";
            if (_apiname == "hgspApi") {
                ePoiId = "77";
            }
            var data = new { ePoiId = ePoiId, orderid = OrdrCode };


            using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"api/MeiTuanAPI/JBP_OrderAPI/queryById") {
                Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")
            }) {
                var client = _httpClientFactory.CreateClient("JdOpenApi");
                using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
                    if (response.IsSuccessStatusCode) {
                        var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        var js = JsonConvert.DeserializeObject<OrderView>(result);
                        return js;
                    }
                }

            }

            return null;
        }
        /// <summary>
        /// Orders the complate task.
        /// </summary>
        /// <returns>The complate task.</returns>
        [HttpGet]
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> OrderComplateTask()
        {
            if (DateTime.Now.Hour > 23) {
                return Ok("");
            }
            if (DateTime.Now.Hour < 7) {
                return Ok("");
            }
            var zmodelist = new List<Zmodel>();
            //Task task = new Task(async () =>
            //{
            var orderlist1 = await _order.GetPayedOrderListAsync<ICasaMielSession>(1).ConfigureAwait(false);

            var orderlist = orderlist1.Where(c => c.ConfrimReceiveTime > DateTime.Now.AddDays(-4)).ToList();
            var meituanorderlist = new List<MtOrderData>();
            if (orderlist.Count > 0) {
                var storelist = await _storeService.GetAllStore<ICasaMielSession>().ConfigureAwait(false);
                foreach (var item in orderlist) {
                    var sentity = storelist.Find(c => c.StoreId == item.StoreId);
                    if (sentity == null) {
                        continue;
                    }
                    if (item.ConfrimReceiveTime.Value > DateTime.Now) {
                        Console.WriteLine(JsonConvert.SerializeObject(item));
                        continue;
                    }
                    var data = new { ePoiId = $"{sentity.RelationId}", orderid = item.OrderCode };
                    using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"api/MeiTuanAPI/JBP_OrderAPI/queryById") {
                        Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")
                    }) {
                        var client = _httpClientFactory.CreateClient("JdOpenApi");
                        using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
                            if (response.IsSuccessStatusCode) {
                                var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                                var js = JsonConvert.DeserializeObject<OrderView>(result);
                                meituanorderlist.Add(js.Data);
                            }
                        }
                    }
                }
                Console.WriteLine(JsonConvert.SerializeObject(meituanorderlist));
                foreach (var item in meituanorderlist) {
                    if (DateTime.Now.Hour > 19) {
                        if (item.LogisticsStatus == 40 || item.LogisticsStatus == 20 || item.Status == 8) {
                            var command = new ThirdOrderPickupCommand(item.OrderId.ToString(CultureInfo.CurrentCulture), 1);
                            var result = await _mediator.Send(command).ConfigureAwait(false);
                            if (result.code == 0) {
                                var entity = orderlist.SingleOrDefault(c => c.OrderCode == $"{item.OrderId}");
                                if (entity != null) {
                                    await _order.OrderOperationLogAddAsync<ICasaMielSession>(new OrderOperationLog {
                                        BillType = 3,
                                        OrderCode = entity.OrderCode,
                                        OrderBaseId = entity.OrderBaseId,
                                        Remark = "美团订单系统定时完成",
                                        CreateTime = DateTime.Now

                                    }).ConfigureAwait(false);
                                }
                                zmodelist.Add(result);


                            }
                            //var entity = await _storeService.GetByOrderCodeAsync<ICasaMielSession>($"{item.orderId}");
                            //if (entity != null)
                            //{
                            //	IcorderpickupDto dto = new IcorderpickupDto()
                            //	{
                            //		//  phoneno = entity.ContactPhone,
                            //		tradeno = entity.IcTradeNO
                            //	};

                            //	var re = await _icApiService.icorderpickup(dto);

                            //	//{ "orderId":"13211703144963360","billno":"NPOS-20180820-0339"}
                            //	logger.Trace($"ComplateTask--,result{JsonConvert.SerializeObject(re)},req:{JsonConvert.SerializeObject(dto)}");
                            //	zmodelist.Add(re);
                            //	if (re.code == 0)
                            //	{
                            //		var jobject = JsonConvert.DeserializeObject<JObject>(re.content);
                            //		var billno = jobject["billno"].ToString();
                            //		//using (var uow = _session.UnitOfWork(IsolationLevel.Serializable))
                            //		//{
                            //		//    entity.ResBillNo = billno;
                            //		//    //entity.OrderStatus = 7;
                            //		//    var s = await _storeService.OrderBaseUPdateAsync(entity, uow);
                            //		//    logger.Trace($"ComplateTask{JsonConvert.SerializeObject(re)}{s}");

                            //		//}
                            //		await _storeService.UpdateOrderStatusAndResBillNOAsync<ICasaMielSession>(entity.OrderBaseId, 7, billno);
                            //		var result = await _storeApiService.MeituanComplate2(entity.OrderCode);
                            //		logger.Trace("MeituanComplateTask:" + result);
                            //	}
                            //}
                        }
                    }
                    //if (item.status == 8 || item.logisticsStatus == 40)
                    //{
                    //var command = new ThirdOrderPickupCommand(item.orderId.ToString(), 1);
                    //var result = await _mediator.Send(command);
                    //if (result.code == 0)
                    //{
                    //	var rsp = await _storeApiService.MeituanComplate2(item.orderId.ToString());
                    //	logger.Trace("MeituanComplateTask:" + rsp);
                    //}
                    //var entity = await _storeService.GetByOrderCodeAsync<ICasaMielSession>($"{item.orderId}");
                    //if (entity != null)
                    //{
                    //	// return Ok(new { code = 9999, msg = "订单不存在" });

                    //	IcorderpickupDto dto = new IcorderpickupDto()
                    //	{
                    //		phoneno = entity.ContactPhone,
                    //		tradeno = entity.IcTradeNO
                    //	};
                    //	var re = await _icApiService.icorderpickup(dto);
                    //	logger.Trace($"ComplateTask--,result{JsonConvert.SerializeObject(re)},req:{JsonConvert.SerializeObject(dto)}");

                    //	zmodelist.Add(re);
                    //	if (re.code == 0)
                    //	{
                    //		var jobject = JsonConvert.DeserializeObject<JObject>(re.content);
                    //		var billno = jobject["billno"].ToString();
                    //		//using (var uow = _session.UnitOfWork(IsolationLevel.Serializable))
                    //		//{
                    //		//    entity.ResBillNo = billno;
                    //		//   // entity.OrderStatus = 7;
                    //		//    var s = await _storeService.OrderBaseUPdateAsync(entity, uow);
                    //		//}
                    //		await _storeService.UpdateOrderStatusAndResBillNOAsync<ICasaMielSession>(entity.OrderBaseId, 7, billno);
                    //		var result = await _storeApiService.MeituanComplate2(entity.OrderCode);
                    //		logger.Trace("MeituanComplateTask:" + result);
                    //	}
                    //}
                    //}
                }
            }
            //});
            //task.Start();
            return Ok(zmodelist);
        }

    }
}
